package com.baidu.sggc.controller;

import com.baidu.sggc.audit.extend.AuditExtendContext;
import com.baidu.sggc.audit.extend.GeneralMessage;
import com.baidu.sggc.core.annotation.AuditLog;
import com.baidu.sggc.core.common.R;
import com.baidu.sggc.data.req.ModelCreateReq;
import com.baidu.sggc.data.req.ModelListReq;
import com.baidu.sggc.data.req.ModelUpdateReq;
import com.baidu.sggc.data.resp.Page;
import com.baidu.sggc.entity.ModelInfo;
import com.baidu.sggc.entity.UserContext;
import com.baidu.sggc.mapper.ModelInfoMapper;
import com.baidu.sggc.service.ModelInfoService;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@RequestMapping("/model")
@Tag(name = "模型信息")
@CrossOrigin(origins = "*")
public class ModelInfoController {

  @Autowired
  private ModelInfoService modelInfoService;

  @Autowired
  private ModelInfoMapper modelInfoMapper;

  @PostMapping("/list")
  @Operation(summary = "模型列表", description = "模型列表")
  @AuditLog(module = "模型管理", auditObject = "模型", operation = "listQuery", message = "查询模型列表")
  public R<Page<ModelInfo>> getModelInfoList(@RequestBody ModelListReq req) {
    // 1. 构建“查询条件”字段
    Map<String, String> condition = new LinkedHashMap<>();
    condition.put("模型名称", req.getModelName());
    // 2. 构建 query_criteria 节点
    Map<String, Object> queryCriteria = new LinkedHashMap<>();
    queryCriteria.put("查询条件", condition);
    // 3. 构建顶层 extendData
    Map<String, Object> extendData = new LinkedHashMap<>();
    extendData.put("query_criteria", queryCriteria);
    // 4. 塞到审计上下文
    AuditExtendContext.setExtendData((Map) extendData);
    return R.ok(modelInfoService.getModelInfoList(req));
  }

  @GetMapping("/detail/{modelId}")
  @Operation(summary = "模型详情", description = "模型详情")
  @AuditLog(module = "模型管理", auditObject = "模型", operation = "detailsQuery", message = "查询模型详情")
  public R<ModelInfo> detail(@PathVariable("modelId") String modelId) {
    Map<String, Object> extendData = new LinkedHashMap<>();
    Map<String, Object> queryCriteria = new LinkedHashMap<>();
    Map<String, Object> condition = new LinkedHashMap<>();
    condition.put("唯一标识", modelId);
    queryCriteria.put("查询条件", condition);
    extendData.put("query_criteria", queryCriteria);
    AuditExtendContext.setExtendData(extendData);
    return R.ok(modelInfoService.getModelDetail(modelId));
  }

  @PostMapping("/create")
  @Operation(summary = "创建模型", description = "创建模型")
  @AuditLog(module = "模型管理", auditObject = "模型", operation = "create", message = "创建模型")
  public R createModel(@RequestBody ModelCreateReq req) {
    ModelInfo modelInfo = new ModelInfo();
    BeanUtils.copyProperties(req, modelInfo);

    String userId = UserContext.getUserId();
    if (userId != null) {
      modelInfo.setCreateId(userId);
    }

    modelInfoMapper.insert(modelInfo); // 插入后 MyBatis-Plus 会回填主键
    Long modelId = modelInfo.getId();  // 回填的主键

    GeneralMessage msg = new GeneralMessage();
    msg.setDataType("模型");
    msg.setDataName(req.getModelName());

    // 现在是 List<String>，用 Collections.singletonList 或 Arrays.asList
    msg.setUniqueIdentification(Collections.singletonList(String.valueOf(modelId)));

    msg.setOperationNum(1);
    AuditExtendContext.setExtendData(toMap(msg));

    return R.ok();
  }

  @PostMapping("/update")
  @Operation(summary = "更新模型", description = "更新模型")
  @AuditLog(module = "模型管理", auditObject = "模型", operation = "update", message = "更新模型")
  public R updateModel(@RequestBody ModelUpdateReq req) {
    req.validate();
    GeneralMessage msg = new GeneralMessage();
    msg.setDataType("模型");
    msg.setDataName(req.getDataType());
    msg.setUniqueIdentification(Collections.singletonList(String.valueOf(req.getId())));
    msg.setOperationNum(1);
    AuditExtendContext.setExtendData(toMap(msg));
    modelInfoService.updateModel(req);
    return R.ok();
  }

  @GetMapping("/project/{projectId}")
  @Operation(summary = "查询模型", description = "查询模型")
  public R<List<ModelInfo>> queryModelsByProjectId(@PathVariable("projectId") String projectId) {
    return R.ok(modelInfoService.queryModelsByProjectId(projectId));
  }

  private Map<String, Object> toMap(Object obj) {
    ObjectMapper mapper = new ObjectMapper();
    return mapper.convertValue(obj, Map.class);
  }
}
